package com.zy.je.common.core.exception;

import cn.dev33.satoken.exception.NotLoginException;
import org.dromara.hutool.core.exception.ExceptionUtil;
import com.zy.je.common.core.web.rest.RestResult;
import com.zy.je.common.core.web.rest.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author zy
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

	/**
	 * 400
	 */
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler({HttpMessageNotReadableException.class,
			MissingServletRequestParameterException.class,
			BindException.class,
			ServletRequestBindingException.class,
			MethodArgumentNotValidException.class
	})
	public RestResult<String> handleHttpMessageNotReadableException(Exception e) {
		if (e instanceof BindException) {
			return new RestResult<>(ResultStatus.BAD_REQUEST, ((BindException) e).getAllErrors().get(0).getDefaultMessage(), null);
		}
		return new RestResult<>(ResultStatus.BAD_REQUEST, e.getMessage(), null);
	}

	/**
	 * 405
	 */
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public RestResult<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
		return new RestResult<>(ResultStatus.METHOD_NOT_ALLOWED);
	}

	/**
	 * 500
	 */
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler({Exception.class, RuntimeException.class})
	public RestResult<String> handleException(Exception e) {
		if (e instanceof AuthException || e instanceof NotLoginException) {
			return new RestResult<>(ResultStatus.INVALID_TOKEN, e.getMessage(), null);
		}
		log.info("{}",e.getMessage(),e);
		if (e instanceof BizException) {
			BizException exp = (BizException) e;
			return e.getMessage().contains("BizException") ?
					new RestResult<>(exp.getErrorCode(), e.getMessage().split("\n")[0].split(": ")[1], null,exp.getDescription()) :
					new RestResult<>(exp.getErrorCode(), e.getMessage(), null,exp.getDescription());
		} else {
			return e.getMessage().contains("BizException") ?
					new RestResult<>(ResultStatus.SYSTEM_ERR, e.getMessage().split("\n")[0].split(": ")[1], (String) null) :
					new RestResult<>(ResultStatus.SYSTEM_ERR, ExceptionUtil.getMessage(e), (String) null);
		}
	}
}
